package ossadaptor

import (
	"encoding/json"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/pkg/logs"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"golang.org/x/net/context"
	"path"
	"strings"
)

type MinioOss struct {
	bindDomain string

	ops    *MinioOssOps
	client *minio.Client
}

type MinioOssOps struct {
	AccessKey string `json:"accessKey"`
	SecretKey string `json:"secretKey"`
	Endpoint  string `json:"endpoint"` // minio服务器地址端口，如：192.168.1.129:9000
	Bucket    string `json:"bucket"`   //bucket名称
	SubPath   string `json:"subPath"`  //子路径，如： download/images
}

func NewMinioOss(bindDomain string, ops *MinioOssOps) (*MinioOss, error) {
	minioClient, err := minio.New(ops.Endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(ops.AccessKey, ops.SecretKey, ""),
		Secure: false,
	})
	if err != nil {
		return nil, err
	}

	if bindDomain == "" {
		bindDomain = ops.Endpoint
	}
	if !strings.HasPrefix(bindDomain, "http") {
		bindDomain = "http://" + bindDomain
	}

	return &MinioOss{
		bindDomain: bindDomain,
		ops:        ops,
		client:     minioClient,
	}, nil
}

func (oss *MinioOss) String() (string, error) {
	bts, err := json.Marshal(oss)
	if err != nil {
		return "", err
	}
	return string(bts), nil
}

func (oss *MinioOss) Parse(s string) error {
	err := json.Unmarshal([]byte(s), oss)
	if err != nil {
		return err
	}
	return nil
}

func (oss *MinioOss) url(info minio.UploadInfo) string {
	logs.Out.Info("Upload= %+v", info)
	return fmt.Sprintf("%s/%s/%s", oss.bindDomain, info.Bucket, info.Key)
}

// Put 上传文件, file: 本地文件路径，objName： minio存储的对象名
func (oss *MinioOss) Put(file string, objName string) (*UploadRet, error) {
	ret := &UploadRet{}
	bucketName := oss.ops.Bucket
	info, err := oss.client.FPutObject(context.Background(),
		bucketName, path.Join(oss.ops.SubPath, objName),
		file, minio.PutObjectOptions{ContentType: ""})
	if err != nil {
		return ret, err
	}

	ret.Url = oss.url(info)

	//println(oss.client.EndpointURL())

	return ret, nil
}
